<?php
/**
 * Created by PhpStorm.
 * User: renyi
 * Date: 2017/7/5
 * Time: 下午17:12
 * Edit: 2019-10-28号修改
 */

namespace App\Base;

use App\Helper\EnvHelper;
use App\Helper\HashIDHelper;
use App\Helper\StringHelper;
use App\Models\Log\AdminDbLog;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Auth;
use Overtrue\LaravelPinyin\Facades\Pinyin;

class BaseModel extends Model
{
    protected $has_hash_id = false;
    protected $pin_yin     = false;

    //重载save
    public function save(array $options = [])
    {
        $oldData = [];
        if ($this->id)
        {
            $oldData = $this->find($this->id);
            $operation= 'update';
        }
        else
        {
            $operation= 'create';
        }

        $this->generate_pin_yin();

//        $this->generateInstitutionId();

        $ret = parent::save($options);

        $this->generateHid();

        $newData = $this->find($this->id);
        $this->saveDbLog($operation, $oldData,$newData);

        return $ret;
    }

    private function generateHid()
    {
        if ($this->has_hash_id == true && !empty($this->id) && (empty($this->hash_id) || strlen($this->hash_id) < 32))
        {
            $this->hash_id = HashIDHelper::encode($this->table, $this->id);
            parent::save();
        }
    }

    private function generateInstitutionId()
    {
        $hasInstitutionId = Schema::hasColumn($this->getTable(), 'institution_id');

        if ($hasInstitutionId)
        {
            $this->institution_id = EnvHelper::currentInstitution()->id ?? 1;
            parent::save();
        }
    }

    public function label($field_name)
    {
        if(is_null($this->$field_name))
        {
            return '';
        }
        else
        {
            return $this->enum[$field_name][$this->$field_name];
        }
    }


    /**
     * Name: delete
     * Desc: 重载删除
     *
     * Author: wangxj
     * Date: 2018/9/28
     * @return bool|null
     * @throws \Exception
     */
    public function delete()
    {
        $oldData = $this->find($this->id);
        $this->saveDbLog('delete', $oldData,'');

        return parent::delete();
    }

    /**
     * Name: saveDbLog
     * Desc: 写入db操作日志
     *
     * Author: wangxj
     * Date: 2018/9/28
     *
     * @param $table
     * @param $operation
     * @param $oldData
     * @param $newData
     */
    protected function saveDbLog($operation,$oldData,$newData)
    {
        $admin = Auth::guard('admin');


        if (empty($admin))
        {
            return;
        }

        $adminUser = $admin->user();
        if (empty($adminUser))
        {
            return;
        }

        $adminId = $adminUser->id;
        if (empty($adminId))
        {
            return;
        }

        // log的写入，不做记录
        $table      = $this->getTable();
        $tableWords = explode('_', $table);
        if (in_array('log', $tableWords))
        {
            return;
        }

        $dbLog = new AdminDbLog();
        $dbLog->admin_id = $adminId;
        $dbLog->table_name = $table;
        $dbLog->operation = $operation;
        $dbLog->old_data = json_encode($oldData);
        $dbLog->new_data = json_encode($newData);

        $dbLog->save();
    }

    public function filterFill($datas)
    {
        $columns = Schema::getColumnListing($this->table);

        foreach ($datas as $k => $v)
        {
            if (!in_array($k, $columns) || is_null($v))
            {
                unset($datas[$k]);
            }
        }

        return $this->fill($datas);
    }

    public function scopeSetHid($query, $hash_id)
    {
        return $query->where('hash_id', $hash_id);
    }

//    protected static function boot()
//    {
//        parent::boot();
//        $institution = EnvHelper::currentInstitution();
//        if ($institution)
//        {
//            static::addGlobalScope('avaiable',function (Builder $builder) use ($institution) {
//                $columnInstitutionId = Schema::hasColumn($builder->getModel()->table, 'institution_id');
//                if ($columnInstitutionId)
//                {
//                    $builder->where('institution_id','=',$institution->id);
//                }
//            });
//        }
//    }

    private function generate_pin_yin()
    {
        if ($this->pin_yin && isset($this->name) && !empty($this->name))
        {
            if (isset($this->pinyin) && empty($this->pinyin))
            {
                $pinyinList = [];

                $name = StringHelper::pickGoodsName($this->name);
                $pinyinList[] = Pinyin::abbr($name);
                $pinyinList[] = Pinyin::permalink($name,'');

                $this->pinyin = implode(',',array_unique($pinyinList));
            }
            else
            {
                if(isset($this->pinyin_first) && empty($this->pinyin_first))
                {
                    $name = StringHelper::pickGoodsName($this->name);
                    $this->pinyin_first = Pinyin::abbr($name);
                }

                if(isset($this->pinyin_full) && empty($this->pinyin_full))
                {
                    $name = StringHelper::pickGoodsName($this->name);
                    $this->pinyin_full = Pinyin::permalink($name,'');
                }
            }

            return $this->pinyin;
        }
        else
        {
            return 0;
        }
    }

}
